#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

#define MAX_CYCLE_NUM 500000

int g_Num = 0;
pthread_mutex_t g_ptmxMute;

void * FunTest1( void * arg )
{
    int i;
    for( i=0; i<MAX_CYCLE_NUM; i++ )
    {
        pthread_mutex_lock( &g_ptmxMute );
        g_Num++;
        pthread_mutex_unlock( &g_ptmxMute );
    }
    printf( "g_Num from 1: %d\n", g_Num );

    return NULL;
}


void * FunTest2( void * arg )
{
    int i;
    for( i=0; i<MAX_CYCLE_NUM; i++ )
    {
        pthread_mutex_lock( &g_ptmxMute );
        g_Num++;
        pthread_mutex_unlock( &g_ptmxMute );
    }
    printf( "g_Num from 2: %d\n", g_Num );

    return NULL;

}

int main(int argc, char const *argv[])
{
    pthread_mutex_init( &g_ptmxMute, NULL );

    pthread_t tpidFunTest1;
    pthread_create( &tpidFunTest1, NULL, FunTest1, NULL );

    pthread_t tpidFunTest2;
    pthread_create( &tpidFunTest2, NULL, FunTest2, NULL );

    pthread_join( tpidFunTest1, NULL );
    pthread_join( tpidFunTest2, NULL );

    pthread_mutex_destroy( &g_ptmxMute );

    return 0;
}

/*

加入互斥锁, 解决共享全局变量的访问资源冲突问题.

*/